package com.qianfeng.mybatis.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtils extends PooledDataSourceFactory {
    //替换datasource为druid的
    public SqlSessionUtils(){
        this.dataSource=new DruidDataSource();
    }
    private static final ThreadLocal<SqlSession> allSession=new ThreadLocal<>();
    //在ThreadLocal中获取sql会话
    public static SqlSession getSession() throws IOException {
        SqlSession sqlSession = allSession.get();
        if (sqlSession==null){
            //通过流加载mybatis.xml
            InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
            //建立数据库连接，创建一个sql会话工厂构建类，参数放流，构建一个会话工厂
            SqlSessionFactoryBuilder sfb=new SqlSessionFactoryBuilder();
            SqlSessionFactory sessionFactory = sfb.build(inputStream);
            //从会话工厂中获取sql会话
            sqlSession = sessionFactory.openSession();
            allSession.set(sqlSession);
        }
        return sqlSession;
    }
    //通过Mapper加载类，返回一个实现类
    public static <T> T getMapper(Class<T> classDao) throws IOException {
        return SqlSessionUtils.getSession().getMapper(classDao);
    }
    //关闭sql会话
    public static void close() throws IOException {
        getSession().close();
        allSession.remove();
    }
    //提交事务
    public static void commit() throws IOException {
        getSession().commit();
    }
}